import React, { useState, useRef, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import { PullToRefresh, VirtualList, InfiniteScroll, NavBar, Image, Tag, Icon, Button } from '@antmjs/vantui';
import Taro, { getMenuButtonBoundingClientRect } from '@tarojs/taro';
import { GetAppList } from "../../../../https/home";
import { HOST, diffTime, getRandomElements } from '../../../../utils/const'
import './index.scss'

const pla = { android: "安卓", ios: "苹果", windows: "windows", mac: 'mac' }

export default function AppVersionList() {
    const instance = Taro?.getCurrentInstance()?.router?.params;
    const btn = getMenuButtonBoundingClientRect();
    const goods = () => {
        const initData = [
            {
                image: 'https://img.yzcdn.cn/vant/cat.jpeg',
                title:
                    '中老年羽绒服男冬季爸爸装薄短款白鸭绒中年人男士保暖外套男装 夜空黑 L【建议115斤以内】',
                price: '¥165.00',
            },
            {
                image: 'https://img.yzcdn.cn/vant/cat.jpeg',
                title: 'HLA海澜之家马丁靴男士高帮男靴复古工装鞋',
                price: '¥361.00',
            },
            {
                image: 'https://img.yzcdn.cn/vant/cat.jpeg',
                title:
                    '洁丽雅拖鞋男夏浴室洗澡防滑家居室内EVA大码男士凉拖鞋居家用夏季防臭 灰色 41-42【标准码】',
                price: '¥22.50',
            },
            {
                image: 'https://img.yzcdn.cn/vant/cat.jpeg',
                title: '夏季新款男士T恤宽松气质高端百搭时尚短袖体恤潮牌',
                price: '¥212.00',
            },
        ]
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(
                    new Array(Math.random() > 0.3 ? 10 : 8).fill('').map((_, index) => {
                        return {
                            index,
                            ...initData[index % 4],
                            isCutPrice: index % 2 === 0 ? true : false,
                        }
                    }),
                )
            }, 1400)
        })
    }
    const [data, setData] = useState([]);
    const mockGoods = goods;
    const infiniteScrollRef = useRef();
    const virtualListRef = useRef();
    const [listData, setListData] = useState([])

    const loadMore = async () => {
        return new Promise(async (resolve) => {
            const result = await mockGoods();
            const newData = data.concat(result);
            setData(newData);
            resolve(newData.length > 110 ? 'loading' : 'complete');
        });
    };

    const onRefresh = () => {
        return new Promise(async (resolve) => {
            infiniteScrollRef.current?.reset();
            const result = await mockGoods();
            await virtualListRef.current?.reset();
            setData(result);
            resolve(undefined);
        });
    };

    useEffect(() => {
        getAPPList()
    }, [])

    const getAPPList = () => {
        Taro.showLoading('加载中')
        GetAppList().then((res) => {
            Taro.hideLoading()
            if (res.data.length > 0) {
                setListData(res.data)
            }
        })
    }

    const navTit = () => {
        switch (Number(instance?.type)) {
            case 1:
                return "新鲜出炉"
                break;
            case 2:
                return "今日好评榜"
                break;
            case 3:
                return "下载排行榜"
                break;
            case 4:
                return "今日下载榜"
                break;
            default:
                break;
        }
    }

    const listItemTitle = (item) => {
        switch (Number(instance?.type)) {
            case 1:
                return `${item?.downloadCnt || 0}人下载`
                break;
            case 2:
                return `${item?.score || 0}人评分`
                break;
            case 3:
                return `${item?.downloadCnt || 0}人下载`
                break;
            case 4:
                return `${item?.downloadCnt || 0}人下载`
                break;
            default:
                break;
        }
    }

    return (
        <View className='mycoins-frame-view'>
            <NavBar title={navTit()} leftArrow leftText={'返回'} onClickLeft={() => Taro.navigateBack()} fixed />
            <View style={{ paddingTop: btn.bottom + 20 }}>
                <PullToRefresh onRefresh={onRefresh} >
                    <VirtualList
                        style={{ padding: 10, boxSizing: 'border-box' }}
                        height="calc(100vh - 135px)"
                        dataSource={getRandomElements(listData, 50)}
                        ref={virtualListRef}
                        showCount={50}
                        footer={
                            <InfiniteScroll
                                parentClassName="van-virtual-list"
                                loadMore={loadMore}
                                ref={infiniteScrollRef}
                            />
                        }
                        ItemRender={({ item }) => {
                            return (
                                <View className='list-bg-view' onClick={() => Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })} >
                                    <View className='img'>
                                        <Image src={HOST + item?.icon} radius={'8%'} width={120} height={120} />
                                    </View>
                                    <View className='info-text'>
                                        <View>
                                            {item?.name}
                                        </View>
                                        <View className='tag-view'>
                                            {item?.score && <><Icon name="star" color="#13b858" size={40} />
                                                <Text className="star-text">{item?.core}</Text></>}
                                            <View className='version-view'>{item?.version || ""}</View>
                                            <View className='version-view'>{item?.create_time ? diffTime(new Date(item?.create_time).getTime()) : '未知'}</View>
                                        </View>
                                        <View className='tag-view'>
                                            <Tag className='tag' type="primary">{item?.platform ? pla[item.platform] : ''}</Tag>
                                            <View className='version-view'>{item?.size || ''}</View>
                                            <View className='separate-veiw'>·</View>
                                            <View className='version-view'>{listItemTitle(item)}</View>
                                        </View>
                                    </View>
                                    <View className='time-view'>
                                        <Button onClick={() => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${item?.link}` })}
                                            className='btn' type='primary' size='mini'>下载</Button>
                                    </View>
                                </View>
                            );
                        }}
                    />
                </PullToRefresh>
            </View>
        </View>
    );
}